import { deepMerge, isPlainObject } from './util';
import { Method } from '../types'

// 请求头中各参数key不区分大小写，例如传参数时（Content-Type也可写成content-type）
function normalizeName(headers: any, normalizedName: string): void {
    if(!headers) {
        return;
    }
    Object.keys(headers).forEach( name => {
        if(name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
            headers[normalizedName] = headers[name];
            delete headers[name]
        }
    })
}
  
/**
 * 处理请求头: 参数data为普通对象，需要将data转化成json字符串
 * 此时也需要同步设置请求头header： Content-Type: application/json; chartset=utf-8
*/ 
export function processHeaders(headers: any, data: any): any {
    normalizeName(headers, 'Content-Type');
    if(isPlainObject(data)) {
        if(headers && !headers['Content-Type']) {
            headers['Content-Type'] = 'application/json;charset=utf-8'
        }
    }
    return headers;
}

// 解析ajax 返回的响应头，转成json对象
export function parseHeaders(headers: string): any {
    let parsed = Object.create(null);
    if(!headers) {
        return
    }

    headers.split("\r\n").forEach(line => {
        let [key, val] = line.split(':');
        key = key.trim().toLocaleLowerCase();
        
        if(!key) {
            return;
        }
        if(val) {
            val = val.trim();
        }
        parsed[key] = val;
    })

    return parsed;
}


// 参见https://www.yuque.com/mapping-pf7di/koz4lo/ni404g  flatten headers
export function flattenHeaders(headers: any, method: Method): any {
    if(!headers) {
        return headers
    }

    headers = deepMerge(headers.common || {}, headers[method] || {}, headers)

    const methodsToDelete = ['delete', 'get', 'head', 'options', 'post', 'put', 'patch', 'common']
    methodsToDelete.forEach(method => {
      delete headers[method]
    })

    return headers;
}